/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "DepositWidget.h"

#include <QtCore/QTime>
#include <QtGui/QEvent.h>
#include <QtGui/QMessageBox>

#include <QtGui/QGridLayout>
#include <QtGui/QPushButton>

#include <QtGui/QHBoxLayout>
#include <QtGui/QTextBlock>
#include <QtGui/QLabel>

#include "QueryManager.h"
#include "PortfolioManager.h"
#include "StockDatabase.h"
#include "DepositCreateDialog.h"
#include "DepositManager.h"

namespace QSThink
{

	DepositWidget::DepositWidget(QWidget *parent,Qt::WindowFlags flag)
		:QWidget(parent,flag),_inited(false),_completer(0),_symbolSelected(false),_itemEdit(false)
	{
		
		setAcceptDrops(true);
		setContextMenuPolicy(Qt::DefaultContextMenu );

		setFocusPolicy(Qt::WheelFocus);
		setMouseTracking(true);
		setMinimumSize(600,400);
	
		setupDataTable();

		QGridLayout *layout = new QGridLayout;

		QLabel* label=new QLabel(tr("Total:"));
		label->setMaximumWidth(64);
		_labelCapital=new QLabel(tr("0"));
		_labelCapital->setMaximumWidth(64);

		layout->addWidget(label, 0, 0);
		layout->addWidget(_labelCapital, 0, 1);
		layout->addWidget(_dataTable, 1, 0,1,3);



		this->setLayout(layout);

		
		loadDeposit();

		_depositCreateDialog=new DepositCreateDialog(this);

		_depositCreateDialog->hide();

		connect(_depositCreateDialog,SIGNAL(OnDepositCreate(DepositInfo *)), this, SLOT(OnDepositCreateFinished(DepositInfo *)));
	}

	
	DepositWidget::~DepositWidget()
	{
		destroy();
	}

	void DepositWidget::loadDeposit()
	{
		
		if(_dataTable->rowCount()==0){
			QAction *createDepositAction=new QAction(QObject::tr("Create Deposit"),_dataTable);
			QAction *removeDepositAction=new QAction(QObject::tr("Remove Deposit"),_dataTable);

			_dataTable->addAction(createDepositAction);
			_dataTable->addAction(removeDepositAction);
			_dataTable->setContextMenuPolicy(Qt::ActionsContextMenu);

			connect(createDepositAction, SIGNAL(triggered()), this, SLOT(createDeposit()));
			connect(removeDepositAction, SIGNAL(triggered()), this, SLOT(removeDeposit()));

		}

		_dataTable->setSortingEnabled(false);
		//_dataTable->clear();
		_dataTable->clearContents();


		int cnt=DepositManager::getSingleton().getDepositCount();
		_dataTable->setRowCount(cnt);

		for (int i=0;i<cnt;++i){
			DepositInfo* info=DepositManager::getSingleton().getDeposit(i);

			// "Date" << "Currency"  << "Type"<< "Balance";
			
			QString accountStr=Utilities::getDepositAccountTypeStr(info->account());


			QDateEdit *dateItem=new QDateEdit(this);
			dateItem->setDate(info->date());
			dateItem->setCalendarPopup(true);

			QComboBox* currencyItem=new QComboBox(this);
			currencyItem->addItem("CNY");
			currencyItem->addItem("HKD");
			currencyItem->addItem("USD");
			currencyItem->addItem("EUR");
			currencyItem->addItem("JPY");
			currencyItem->addItem("CAD");
			currencyItem->addItem("AUD");
			currencyItem->setCurrentIndex(info->currency());

			QComboBox* accountItem=new QComboBox(this);
			accountItem->addItem("Cash");
			accountItem->addItem("3 Month");
			accountItem->addItem("6 Month");
			accountItem->addItem("12 Month");
			accountItem->addItem("24 Month");
			accountItem->addItem("36 Month");
			accountItem->addItem("60 Month");
			accountItem->setCurrentIndex(info->account());

			QTableWidgetItem *balanceItem = new QTableWidgetItem(QString::number(info->balance()));

			_dataTable->setCellWidget(i,0, dateItem);
			_dataTable->setCellWidget(i,1,currencyItem);
			_dataTable->setCellWidget(i,2, accountItem);
			_dataTable->setItem(i,3, balanceItem);
			

			
			_itemToDeposits.insert(ItemToDepositInfoMap::value_type(dateItem,info));

		}
		
		capitalCalc();

		_dataTable->setSortingEnabled(true);
		_dataTable->sortItems(0,Qt::AscendingOrder);

	}
	
	void DepositWidget::removeDeposit()
	{
		int row=_dataTable->currentRow();

		QWidget* w=_dataTable->cellWidget(row,0);

		ItemToDepositInfoMap::iterator it=_itemToDeposits.find(w);
		if(it!=_itemToDeposits.end()){
			//find
			DepositInfo* info= it->second;
			DepositManager::getSingleton().removeDeposit(info);
			_itemToDeposits.erase(it);

		}

		_dataTable->removeRow(row);

		capitalCalc();
	}

	
	
	void DepositWidget::tableItemChanged( QTableWidgetItem * item )
	{
		if(!_itemEdit){
			_itemEdit=false;
			return;
		}
		int row=item->row();
		int col=item->column();

		if(col==3){
			QString text= item->text();
			bool success=false;
			int balance=text.toInt(&success);
			if(success){
				capitalCalc();
				return;
			}else{
				//recover if not allowed
				item->setText(_selectedText);
			}
		}

	}

	void DepositWidget::tableItemDoubleClicked( QTableWidgetItem * item )
	{
		int col=item->column();
		if(col==3){
			_itemEdit=true;
			_selectedText= item->text();
		}
	}

	void DepositWidget::setupDataTable()
	{
		//Name	Symbol	Last price	Change	 Mkt cap	Volume	Open	High	Low	Day's gain
		QStringList headers;
		headers << "Date" << "Currency"  << "Type"<< "Balance";

		_dataTable=new QTableWidget(0,headers.size());
		_dataTable->setSelectionBehavior ( QAbstractItemView::SelectRows); 
		_dataTable->setSelectionMode ( QAbstractItemView::SingleSelection); 
		_dataTable->setSortingEnabled(false);
		_dataTable->setContextMenuPolicy(Qt::NoContextMenu);


		_dataTable->setHorizontalHeaderLabels(headers);
		_dataTable->setSortingEnabled(false);
		connect(_dataTable,SIGNAL(itemChanged(QTableWidgetItem *)),this,SLOT(tableItemChanged(QTableWidgetItem *)));
		connect(_dataTable,SIGNAL(itemDoubleClicked(QTableWidgetItem *)),this,SLOT(tableItemDoubleClicked(QTableWidgetItem *)));
	}

	
	
	void DepositWidget::capitalCalc()
	{
		float total=0;
		int cnt=_dataTable->rowCount();
		for(int i=0;i<cnt;++i){
			QTableWidgetItem* item=_dataTable->item(i,3);
			if(!item){
				//just return when data is not ready
				return;
			}
			float capital=item->text().toFloat();
			total+=capital;
		}

		_labelCapital->setText(QString::number(total));

	}

	void DepositWidget::createDeposit()
	{
		_depositCreateDialog->show();
		
	}

	void DepositWidget::OnDepositCreateFinished( DepositInfo* info)
	{
		insertDepositRow(info);



	}

	void DepositWidget::insertDepositRow( DepositInfo* info )
	{
		_dataTable->setSortingEnabled(false);

		DepositCurrencyType currency=info->currency();
		DepositAccountType account=info->account();
		int balance=info->balance();
		QDate date=info->date();

		QString currencyText=Utilities::getDepositCurrencyTypeStr(currency);
		QString accountText=Utilities::getDepositAccountTypeStr(account);
		QString balanceText=QString::number(balance);

		QDateEdit *dateItem=new QDateEdit(this);
		dateItem->setDate(info->date());
		dateItem->setCalendarPopup(true);

		QComboBox* currencyItem=new QComboBox(this);
		currencyItem->addItem("CNY");
		currencyItem->addItem("HKD");
		currencyItem->addItem("USD");
		currencyItem->addItem("EUR");
		currencyItem->addItem("JPY");
		currencyItem->addItem("CAD");
		currencyItem->addItem("AUD");
		currencyItem->setCurrentIndex(info->currency());


		QComboBox* accountItem=new QComboBox(this);
		accountItem->addItem("Cash");
		accountItem->addItem("3 Month");
		accountItem->addItem("6 Month");
		accountItem->addItem("12 Month");
		accountItem->addItem("24 Month");
		accountItem->addItem("36 Month");
		accountItem->addItem("60 Month");
		accountItem->setCurrentIndex(info->account());

		QTableWidgetItem *balanceItem = new QTableWidgetItem(balanceText);

		int row=_dataTable->rowCount();
		_dataTable->insertRow(row);

		_dataTable->setCellWidget(row,0, dateItem);
		_dataTable->setCellWidget(row,1, currencyItem);
		_dataTable->setCellWidget(row,2, accountItem);
		_dataTable->setItem(row,3, balanceItem);

		_dataTable->setSortingEnabled(true);

		_itemToDeposits.insert(ItemToDepositInfoMap::value_type(dateItem,info));

		capitalCalc();

	}

}
